﻿using System;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using BIPorter.Common.DAL;
using BIPorter.Common.Model;

namespace BIPorter.Common.BLL
{
    public class AccountBll
    {
        AccountDAL AccountDAL = new AccountDAL();

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public OperationResult Login(string userName, string password, bool rememberMe=false)
        {
            OperationResult res = new OperationResult();
            int cookieTime = Convert.ToInt16(PathHelper.GetSettings("ExpirationTime"));
            //TODO 测试 此处员工编号暂时取测试
            var model = AccountDAL.GetUserInfo("sunsf01");

            string err = string.Empty;
            bool loginRes = this.ValidateAD(userName, password, out err);
            if (loginRes&&model!=null)
            {
                res.Result = loginRes;
                res.AppendData = model;
                HttpContext context = HttpContext.Current;
                #region 票据
                FormsAuthentication.SetAuthCookie(model.UserName, rememberMe);
                //票据
                string data = string.Empty;
                if (model != null)
                    data = (new JavaScriptSerializer()).Serialize(model);
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                     2, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(cookieTime), true, data);

                // 根据加密结果创建登录Cookie
                string cookieValue = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
                cookie.HttpOnly = true;
                cookie.Secure = FormsAuthentication.RequireSSL;
                cookie.Domain = FormsAuthentication.CookieDomain;
                cookie.Path = FormsAuthentication.FormsCookiePath;
                cookie.Expires = DateTime.Now.AddMinutes(cookieTime);

                // 写登录Cookie
                context.Response.Cookies.Remove(cookie.Name);
                context.Response.Cookies.Add(cookie);
                ///
                #endregion
            }
            else
            {
                res.Exception = err;
                res.Result = loginRes;
            }
            return res;
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        public static AccountModel GetCurrentUser()
        {
            HttpContext context = HttpContext.Current;
            AccountModel model = null;
            // 1. 读登录Cookie

            HttpCookie cookie =context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (!(cookie == null || string.IsNullOrEmpty(cookie.Value)))
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false) 
                    // 3. 还原用户数据
                    model = new JavaScriptSerializer().Deserialize<AccountModel>(ticket.UserData);
            }
            return model;
        }

        //域账户登陆
        public bool ValidateAD(string userID, string password, out string err)
        {
            try
            {
                string serviceUrl = PathHelper.GetSettings("ADLogin");
                StringBuilder parms = new StringBuilder();
                parms.Append("{");
                parms.Append(string.Format("\"UserID\":\"{0}\",\"Password\":\"{1}\"", userID, password));
                parms.Append("}");
                err = CommonHelper.RequestService(serviceUrl, string.Empty, parms.ToString(), "POST", "application/json");
                if (err.Contains("ErrorCode"))
                {
                    err = "登陆失败用户名密码错误!";
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                err = "认证服务器有问题";
                return false;
            }
        }

        //END

    }
}
